'''
线程安全问题
    -多个线程同时操作共享变量，有可能导致出错
    -解决方法：添加锁
    -添加锁后，会保证线程的安全，但是会降低代码的执行效率
'''

import time, threading


# 银行账户余额
balance = 0
# 创建锁
lock = threading.Lock()

def change(money):
    # 声明全局变量balance
    global balance
    # 存钱
    balance = balance + money
    # 取钱
    balance = balance - money


def play(money):
    for i in range(10000000):
        # 上锁(获取锁)
        lock.acquire()

        change(money)

        # 解锁(释放锁)
        lock.release()

t1 = threading.Thread(target=play,args=(100,))
t2 = threading.Thread(target=play,args=(50,))

t1.start()
t2.start()
t1.join()
t2.join()
print('balance=%d'%balance)